import 'dart:convert';
import 'dart:core';

import 'package:ecy_app_flutter/constant/EcyEventConsnt.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:ecy_app_flutter/routes/goods/model/EcyGoodsHomeCategoryListModel.dart';
import 'package:ecy_app_flutter/routes/goods/widgets/EcyGoodsCategoryListView.dart';
import 'package:ecy_app_flutter/routes/goods/widgets/EcyGoodsHomeIPListView.dart';
import 'package:ecy_app_flutter/routes/goods/widgets/EcyGoodsSkuListView.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:ecy_app_flutter/ecycommon/EcyRequestBaseManager.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../EcyRouter.dart';
import '../../../ecycommon/EcyEventBus.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../model/EcyGoodsHomeCategoryModel.dart';
import '../model/EcyGoodsHomeIPListModel.dart';
import '../model/EcyGoodsHomeIPModel.dart';
import '../model/EcyGoodsSkuListModel.dart';

class EcyGoodsFirstPage extends StatefulWidget {
  late _EcyGoodsFirstPageState state;

  EcyGoodsFirstPage({required super.key});

  @override
  State<StatefulWidget> createState() {
    state = _EcyGoodsFirstPageState();
    return state;
  }

  reloadData() {
    state.requestData();
  }
}

class _EcyGoodsFirstPageState extends State<EcyGoodsFirstPage> {
  EcyGoodsSkuListModel skuListModel = EcyGoodsSkuListModel(0, 0, 0, 0, []);
  EcyGoodsHomeCategoryListModel categoryListModel =
      EcyGoodsHomeCategoryListModel(0, 0, 0, []);
  int ipIndex = 0;
  int categoryIndex = 0;
  late EcyGoodsHomeIPListView ipListView;
  late EcyGoodsSkuListView skuListView;
  late EcyGoodsCategoryListView categoryListView;

  EcyGoodsHomeIPModel selectIPModel =
      EcyGoodsHomeIPModel("", "", "", "", "", false, false, "");
  EcyGoodsHomeCategoryModel selectCategoryModel =
      EcyGoodsHomeCategoryModel("", "", "", "", false, 0, "");

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int _currentPage = 1;
  bool _hasMore = false;

  @override
  void initState() {
    super.initState();

    initNotis();

    ipListView = EcyGoodsHomeIPListView((newValue) {
      if (newValue != null && newValue.id == '-2') {
        EcyRouter().pushWithNeedLogin(context, EcyRouter.ipSelectPage,
            {EcyRouter.kTargetUrl: EcyRouter.ipSelectPage}, (newValue) {
          if (newValue != null) {
            ipListView.refreshData();
          }
        });
      } else {
        selectIPModel = newValue;
        _currentPage = 1;
        requestSkuListData();
      }
    });
    categoryListView =
        EcyGoodsCategoryListView(categoryListModel, 0, (newValue) {
      selectCategoryModel = newValue;
      _currentPage = 1;
      requestSkuListData();
    });
    skuListView = EcyGoodsSkuListView(skuListModel, 0, (page) {
      _currentPage = 1;
      requestSkuListData();
    });

    requestData();
  }

  initNotis() {
    EcyEventBus().on(EcyEventConst.kLogined, (arg) {
      requestData();
    });
    EcyEventBus().on(EcyEventConst.kHttpConnected, (arg) {
      requestData();
    });
  }

  @override
  void requestData() async {
    if (mounted) {
      requestHeadData();
      _currentPage = 1;
      requestSkuListData();
    }
  }

  //批量查询首页lable、ip、category数据
  Future<bool> requestHeadData() async {
    List<Map<String, dynamic>> response = [];
    try {
      response = await Future.wait([
        EcyRequestbasemanager().post("/app/api/app/commodityIp/list",
            {"size": "50", "current": "1", "name": ""}),
        EcyRequestbasemanager().post("/app/api/app/commodityCategory/list",
            {"size": "50", "current": "1", "name": ""}),
      ]);
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
    if (response.isNotEmpty) {
      var ipResp = response[0];
      if (ipResp != null) {
        reloadIPArea(ipResp);
      }

      var categoryResp = response[1];
      if (categoryResp != null) {
        reloadCategoryArea(categoryResp);
      }
    }
    return true;
  }

  //查询商品列表
  Future<bool> requestSkuListData() async {
    try {
      Map<String, dynamic> response =
          await EcyRequestbasemanager().post("/app/api/app/commodity/list", {
        "size": "10",
        "current": _currentPage,
        "name": "",
        "status": "1",
        "ipCode": selectIPModel.code == "-1" ? "" : selectIPModel.code,
        "categoryCode":
            selectCategoryModel.code == "-1" ? "" : selectCategoryModel.code,
      });
      reloadSKUArea(response);
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
    return true;
  }

  void reloadIPArea(ipResp) {
    try {
      var ipRespModel = EcyApiCommonResponse.fromJson(ipResp, (ipResp) => json);
      if (ipRespModel.code == 0 || ipRespModel.code == 200) {
        EcyGoodsHomeIPListModel _ipListModel =
            EcyGoodsHomeIPListModel.fromJson(ipResp["data"]);
        ipListView.reloadData(_ipListModel);
      }
    } catch (e) {
      EcyLogger.log("获取IP失败");
    }
  }

  void reloadCategoryArea(_categoryResp) {
    var _cateogryRespModel =
        EcyApiCommonResponse.fromJson(_categoryResp, (_categoryResp) => json);
    if (_cateogryRespModel.code == 0 || _cateogryRespModel.code == 200) {
      EcyGoodsHomeCategoryListModel _labelListModel =
          EcyGoodsHomeCategoryListModel.fromJson(_categoryResp["data"]);
      var all = EcyGoodsHomeCategoryModel(
          "全部", "全部", "-1", "assets/images/ic_home_allip.png", true, 0, "-1");
      _labelListModel.records.insert(0, all);
      if (_labelListModel.records.isNotEmpty) {
        this.selectCategoryModel = _labelListModel.records.first;
      }
      categoryListView.reloadData(_labelListModel);
    }
  }

  void reloadSKUArea(_skuResp) {
    var commonResponse =
        EcyApiCommonResponse.fromJson(_skuResp, (_skuResp) => json);
    if (commonResponse.code == 0 || commonResponse.code == 200) {
      EcyGoodsSkuListModel currSkuListModel =
          EcyGoodsSkuListModel.fromJson(_skuResp["data"]);
      _hasMore = currSkuListModel.pages > _currentPage;
      _currentPage = currSkuListModel.current;
      if (_currentPage == 1) {
        skuListModel = currSkuListModel;
      } else {
        skuListModel.records.addAll(currSkuListModel.records);
      }
      skuListView.reloadData(skuListModel, _currentPage);
    }
  }

  void requestAllCategorys() async {}

  //下拉刷新
  Future<void> _onRefresh() async {
    _currentPage = 1;
    await requestSkuListData();
    _refreshController.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading() async {
    if (_hasMore) {
      _currentPage++;
      await requestSkuListData();
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const Padding(padding: EdgeInsets.only(bottom: 8)),
        Container(
            color: const Color(0xFFFFFFFF),
            width: MediaQuery.of(context).size.width,
            height: 75.w,
            child: SizedBox.fromSize(
              size: Size(MediaQuery.of(context).size.width, 75.w),
              child: ipListView,
            )),
        Container(
            color: const Color(0xFFFFFFFF),
            width: MediaQuery.of(context).size.width,
            height: 50.w,
            child: SizedBox.fromSize(
              size: Size(MediaQuery.of(context).size.width, 50.w),
              child: categoryListView,
            )),
        Flexible(
          child: Container(
            color: const Color(0xFFF5F5F5),
            child: SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              physics: const AlwaysScrollableScrollPhysics(),
              header: const ClassicHeader(
                refreshStyle: RefreshStyle.Follow,
                idleText: '下拉刷新',
                refreshingText: '加载中...',
                completeText: '刷新完成',
                failedText: '刷新失败',
                textStyle:
                TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
                releaseText: '松开刷新',
                iconPos: IconPosition.top,
                spacing: 8,
              ),
              footer: CustomFooter(
                builder: (BuildContext context, LoadStatus? mode) {
                  Widget body;
                  if (mode == LoadStatus.idle) {
                    body = const Text("上拉加载更多",
                        style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.loading) {
                    body = const Text("加载中...",
                        style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.failed) {
                    body = const Text("加载失败，点击重试",
                        style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else if (mode == LoadStatus.canLoading) {
                    body = const Text("松手加载更多",
                        style: TextStyle(color: Color(0xFF8C8C8C)));
                  } else {
                    body = const Text("没有更多商品了",
                        style: TextStyle(color: Color(0xFF8C8C8C)));
                  }
                  return SizedBox(
                    height: 35.w,
                    child: Center(child: body),
                  );
                },
              ),
              onRefresh: () => _onRefresh(),
              onLoading: () => _onLoading(),
              controller: _refreshController,
              child: skuListView,
            ),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
    _refreshController.dispose();
  }
}
